package com.luoran.bartalks.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.beetl.sql.core.RowMapper;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.luoran.bartalks.service.IF4TreeService;

/**
 * @author lifetime
 *
 */
@Service
public class F4TreeService implements IF4TreeService {
	@Autowired
	private SQLManager sqlManager;

	/**
	 * 数据格式[{id:1, pId:0, name:"演示", level:1, open:false}]
	 * 
	 * @see com.luoran.bartalks.service.IF4TreeService#tree(java.lang.String)
	 */
	@Override
	public List<HashMap> tree(String sign, Map<String, Object> params, String[] fields, Integer openLevel) {
		return sqlManager.select("f4tree." + sign, HashMap.class, params, new RowMapper<HashMap>() {
			public HashMap mapRow(Object obj, ResultSet rs, int rowNum) throws SQLException {
				HashMap<String, Object> map = new HashMap<>();
				map.put("id", rs.getObject("id"));
				map.put("name", rs.getString("name"));
				map.put("pId", rs.getObject("pid"));
				if(fields != null){
					for (String qf : fields) {
						map.put(qf, rs.getObject(qf));
					}
				}
				if(openLevel != null){
					Object levelObj = rs.getObject("level");
					if (levelObj != null) {
						if (((Integer) levelObj) <= openLevel) {
							map.put("open", Boolean.TRUE);
						}
					}
				}
				return map;
			}
		});
	}

	@Override
	public List<HashMap> tree(String sign) {
		return tree(sign, null, null, null);
	}

	@Override
	public List<HashMap> tree(String sign, String[] fields, Integer openLevel) {
		return tree(sign, null, fields, openLevel);
	}

	@Override
	public List<HashMap> tree(String sign, Integer openLevel) {
		return tree(sign, null, null, openLevel);
	}

}
